// Log.hpp
#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <time.h>
#include <cstdarg>
#include <iomanip>
#include <chrono>
#include <ctime>
#include <sstream>
using namespace std;

enum
{
    Debug = 0,
    Information,
    Warning,
    Error,
    Fatal,
    Unknown
};

//将错误等级转换成字符串
string leveltostring(int level)
{
    switch (level)
    {
    case 0:
        return string("Debug");
    case 1:
        return string("Information");
    case 2:
        return string("Warning");
    case 3:
        return string("Error");
    case 4:
        return string("Fatal");
    default:
        return string("Unknown");
    }
}

// 获取时间
string timetostring()
{
    // time_t t = time(nullptr);
    // struct tm *time = localtime(&t);
    // string str;
    // str += to_string(time->tm_hour);
    // str += to_string(time->tm_min);
    // str += to_string(time->tm_sec);
    // return str;

    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    stringstream nowtime;
    nowtime<<put_time(std::localtime(&now_c), "%Y-%m-%d %H:%M:%S");
    return nowtime.str();
}

// 日志格式：日志等级 时间 pid 消息体
void LogMessage(int level, char *format...)
{
    char leftmeg[1024];
    char rightmeg[1024];
    
    //日志等级
    string levelstr = leveltostring(level);
    //获取时间
    string timestr = timetostring();
    snprintf(leftmeg, sizeof(leftmeg), "等级：%s,时间：%s,pid:%d,消息：", levelstr.c_str(), timestr.c_str(), getpid());

    //对可变参数进行处理
    va_list p;           // char*
    va_start(p, format); // p指向可变参数部分的起始地址
    vsnprintf(rightmeg, sizeof(rightmeg), format, p);
    va_end(p);

    // cout<<leftmeg<<rightmeg<<endl;

    // 写入文件
    FILE *fp = fopen("./log.txt", "a");
    fprintf(fp, "%s%s\n", leftmeg, rightmeg);
    fflush(fp);
    fclose(fp);
}
